package com.csthink.auditlog.config.parser;

import com.csthink.auditlog.annotation.AuditLogField;
import com.csthink.auditlog.domain.AuditLog;
import com.csthink.auditlog.domain.Change;
import com.csthink.auditlog.enums.ActionEnum;
import com.csthink.auditlog.enums.CategoryEnum;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-12
 */
public class AuditLogDetailParser implements BeanFactoryAware {

    private Map<String, Map<Field, AuditLogField>> cachedMapping = new ConcurrentHashMap<>();
    private ExpressionParser parser = new SpelExpressionParser();

    private BeanFactoryResolver beanFactoryResolver;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactoryResolver = new BeanFactoryResolver(beanFactory);
    }

    public String parse(AuditLog auditLog) {
        if (auditLog == null || CollectionUtils.isEmpty(auditLog.getChanges())) {
            return null;
        }
        List<Change> changes = auditLog.getChanges();
        List<String> changeDetails = null;
        switch (ActionEnum.getAction(auditLog.getAction())) {
            case ADD:
                changeDetails = parseOne(changes, c -> c.getRawNewValue());
                break;
            case UPDATE:
                changeDetails = parseBoth(changes);
                if(CollectionUtils.isEmpty(changeDetails)){
                    auditLog.setWriteRecord(false);
                    return "";
                }
                break;
            case MOVE:
                changeDetails = parseBoth(changes);
                if(CollectionUtils.isEmpty(changeDetails)){
                    auditLog.setWriteRecord(false);
                    return "";
                }
                break;
            case DELETE:
                changeDetails = parseOne(changes, c -> c.getRawOldValue());
                break;
        }
        if (CollectionUtils.isEmpty(changeDetails)) {
            return null;
        }
        String detail;
        if (changeDetails.size() == 1) {
            detail = changeDetails.get(0);
        }
        else {
            detail = "\n" + Joiner.on("\n ").join(changeDetails);
        }
        return String.format("{{alg.action.%s}} {{alg.category.%s}}: %s",
                StringUtils.lowerCase(auditLog.getAction()),
                Optional.ofNullable(CategoryEnum.parse(auditLog.getCategory())).orElse(CategoryEnum.UNKNOWN).getName(),
                detail);
    }

    private List<String> parseOne(List<Change> changes, Function<Change, Object> valueGetter) {
        List<String> changeDetails = new ArrayList<>();
        for (int i = 0; i < changes.size(); i++) {
            Change change = changes.get(i);

//            List<String> cs = parse(valueGetter.apply(change));
            changeDetails.add(String.format("%s", change.getKeyword()));
        }
        return changeDetails;
    }

    private List<String> parseBoth(List<Change> changes) {
        List<String> changeDetails = new ArrayList<>();
        String keyword = null;
        for (int i = 0; i < changes.size(); i++) {
            Change change = changes.get(i);
            keyword = Strings.isNullOrEmpty(keyword)?change.getKeyword():keyword;
            List<Triple<String,String, String>> changeFields = parse(change.getRawOldValue(), change.getRawNewValue());
            List<String> changeList = Lists.newArrayList();
            for(Triple<String,String, String> field : changeFields){
                if(Strings.isNullOrEmpty(field.getMiddle()) && Strings.isNullOrEmpty(field.getRight())){
                    continue;
                }else if(Strings.isNullOrEmpty(field.getMiddle())){
                    changeList.add(String.format("[{{alg.field.%s}} {{alg.event.to}}: %s]", field.getLeft(), field.getRight()));
                }else if(Strings.isNullOrEmpty(field.getRight())){
                    changeList.add(String.format("[{{alg.field.%s}} {{alg.event.from}}: %s]", field.getLeft(), field.getMiddle()));
                }else  {
                    changeList.add(String.format("[{{alg.field.%s}} {{alg.event.from}}: %s {{alg.event.to}}: %s]", field.getLeft(), field.getMiddle(), field.getRight()));
                }
            }
            if(!CollectionUtils.isEmpty(changeList)) {
                String valueStr = Joiner.on(" \n ").join(changeList);
                changeDetails.add(String.format("%s %s", keyword, valueStr));
            }
        }
        return changeDetails;
    }

    private List<Triple<String,String, String>> parse(Object oldVal, Object newVal) {
        if (Objects.isNull(oldVal) && Objects.isNull(newVal)) {
            return Collections.emptyList();
        }
        var fieldMap = parseFields(Objects.isNull(oldVal) ? newVal : oldVal);
        if(CollectionUtils.isEmpty(fieldMap)){
            return Collections.emptyList();
        }

        List<Triple<String,String, String>> values = new ArrayList<>();
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setBeanResolver(beanFactoryResolver);

        Map<Field,Object> oldValueMap = getObjectValueMap(oldVal);
        Map<Field,Object> newValueMap = getObjectValueMap(newVal);

        fieldMap.forEach((field, anno) -> {
            ReflectionUtils.makeAccessible(field);
            Object oldFieldVal = ReflectionUtils.getField(field, oldVal);
            Object newFieldVal = ReflectionUtils.getField(field, newVal);

            var mapping = anno.value();
            if (!Objects.equals(oldFieldVal, newFieldVal)) {
                String oldStr = eval(context, getExpr(mapping,oldValueMap), oldFieldVal);
                String newStr = eval(context, getExpr(mapping,newValueMap), newFieldVal);
                values.add(Triple.of(field.getName(), oldStr, newStr));
            }
        });
        return values;
    }

    private Pattern paramKeyWord = Pattern.compile("\\{\\{[\\w.]*\\}\\}",Pattern.CASE_INSENSITIVE);

    private Expression getExpr(String mapping, Map<Field,Object> valueMap){
        if(mapping.indexOf("@")>=0 && paramKeyWord.matcher(mapping).find()){
            Matcher m = paramKeyWord.matcher(mapping);
            StringBuffer sb = new StringBuffer();
            while(m.find()){
                String currentMather = m.group();
                String fieldName = currentMather.substring(2,currentMather.length()-2);
                String valueStr = null;
                for(Field f : valueMap.keySet()){
                    if(f.getName().equals(fieldName)){
                        valueStr = String.valueOf(valueMap.get(f));
                    }
                }
                if(Strings.isNullOrEmpty(valueStr)){
                    m.appendReplacement(sb, "null");
                }else {
                    m.appendReplacement(sb, valueStr);
                }
            }
            m.appendTail(sb);
            Expression expr = parser.parseExpression(sb.toString());
            return expr;
        }else{
            return parser.parseExpression(mapping);
        }

    }

    private List<Field> getDeclaredFieldsOfClazz(Class clazz){
        List<Field> fieldList = Lists.newArrayList(clazz.getDeclaredFields());
        if(!"Object".equals(clazz.getSuperclass().getName())){
            fieldList.addAll(Lists.newArrayList(clazz.getSuperclass().getDeclaredFields()));
        }
        return fieldList;
    }

    private Map<Field,Object> getObjectValueMap(Object obj){
        if (Objects.isNull(obj)) {
            return Collections.emptyMap();
        }
        Class clazz = obj.getClass();
        List<Field> fieldList = getDeclaredFieldsOfClazz(clazz);
        Map<Field, Object> fieldMap = new HashMap<>();
        for (Field field : fieldList) {
            ReflectionUtils.makeAccessible(field);
            Object fieldVal = ReflectionUtils.getField(field, obj);
            fieldMap.put(field, fieldVal);
        }
        return fieldMap;
    }

    private Map<Field, AuditLogField> parseFields(Object obj) {
        if (Objects.isNull(obj)) {
            return Collections.emptyMap();
        }
        Class clazz = obj.getClass();
        if (!cachedMapping.containsKey(clazz.getName())) {
            Map<Field, AuditLogField> fieldMap = new HashMap<>();
            List<Field> fieldList = getDeclaredFieldsOfClazz(clazz);
            for (Field f : fieldList) {
                AuditLogField annotation = f.getAnnotation(AuditLogField.class);
                if (Objects.nonNull(annotation)) {
                    fieldMap.put(f, annotation);
                }
            }

            cachedMapping.put(clazz.getName(), fieldMap);
        }
        return cachedMapping.get(clazz.getName());
    }

    private String eval(EvaluationContext context, Expression expression, Object val) {
        try {
            context.setVariable("value", val);
            return expression.getValue(context, String.class);
        } catch (Exception e) {
            logger.error("Fail to eval spel expression: {}", expression.getExpressionString(), e);
        }
        return null;
    }
}
